<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Cursor Tooltip w/placement.js</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="../dist/uPlot.min.css">
		<style>
			#overlay {
				position: absolute;
				background: rgba(0, 0, 0, 0.8);
				padding: 0.5rem;
				margin: 0.75rem;
				color: #fff;
				z-index: 10;
				pointer-events: none;
			}
		</style>
	</head>
	<body>
		<script src="../dist/uPlot.iife.js"></script>
		<script src="lib/placement.min.js"></script>
		<script>
			function tooltipPlugin(opts) {
				let over, bound, bLeft, bTop;

				function syncBounds() {
					let bbox = over.getBoundingClientRect();
					bLeft = bbox.left;
					bTop = bbox.top;
				}

				const overlay = document.createElement("div");
				overlay.id = "overlay";
				overlay.style.display = "none";
				overlay.style.position = "absolute";
				document.body.appendChild(overlay);

				return {
					hooks: {
						init: u => {
							over = u.over;

							bound = over;
						//	bound = document.body;

							over.onmouseenter = () => {
								overlay.style.display = "block";
							};

							over.onmouseleave = () => {
								overlay.style.display = "none";
							};
						},
						setSize: u => {
							syncBounds();
						},
						setCursor: u => {
							const { left, top, idx } = u.cursor;
							const x = u.data[0][idx];
							const y = u.data[1][idx];
							const anchor = { left: left + bLeft, top: top + bTop };
							overlay.textContent = `${x},${y} at ${Math.round(left)},${Math.round(top)}`;
							placement(overlay, anchor, "right", "start", { bound });
						}
					}
				};
			}

			const opts = {
				id: "chart",
				title: "placement.js tooltip",
				width: 600,
				height: 400,
				plugins: [
					tooltipPlugin(),
				],
				scales: {
					x: {
						time: false,
					}
				},
				series: [
					{},
					{
						label: "blah",
						width: 1,
						stroke: "green"
					}
				]
			};

			const data = [
				[ 1,  2,  3,  4,  5,  6,  7],
				[40, 43, 60, 65, 71, 73, 80]
			];

			const u = new uPlot(opts, data, document.body);
		</script>
	</body>
</html>